package com.tz.colawallet.basecode.base;

import android.text.TextUtils;

import com.tz.colawallet.basecode.comm.MyApplication;
import com.tz.colawallet.basecode.event.NetErrorEvent;
import com.tz.colawallet.basecode.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.net.ConnectException;
import java.net.UnknownHostException;

import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;

/**
 * Created by xuweihua on 16/5/31.
 */
public abstract class BaseSubscribe<T> extends Subscriber<T> {
    private String track;

    public String getTrack() {
        return track;
    }

    public void setTrack(String track) {
        this.track = track;
    }

    @Override
    public void onCompleted() {

    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        String errorMsg = e.getMessage();
        if (TextUtils.isEmpty(errorMsg)) {
            errorMsg = "服务器连接失败,请稍后再试";
        }
        NetErrorEvent errorEvent = new NetErrorEvent();
        errorEvent.setTrack(track != null ? track : "");
        if (e instanceof UnknownHostException || e instanceof ConnectException) {
            errorMsg = "无法连接服务器,请检查手机网络";
            errorEvent.setLevel(0);
        } else if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
//            switch (httpException.code()){}
            errorEvent.setLevel(0);
        } else {
            errorEvent.setLevel(1);
        }
        EventBus.getDefault().post(errorEvent);
        ToastUtil.showText(MyApplication.context, errorMsg);
    }

    @Override
    public abstract void onNext(T t);
}
